import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import 'package:openim_common/src/widgets/chat/voice_record_bar.dart';

import 'chat_logic.dart';

class ChatPage extends StatelessWidget {
  final logic = Get.find<ChatLogic>(tag: GetTags.chat);

  ChatPage({super.key});

  Widget _buildItemView(Message message) => ChatItemView(
        key: logic.itemKey(message),
        message: message,
        textScaleFactor: logic.scaleFactor.value,
        allAtMap: logic.getAtMapping(message),
        timelineStr: logic.getShowTime(message),
        sendStatusSubject: logic.sendStatusSub,
        leftNickname: logic.getNewestNickname(message),
        leftFaceUrl: logic.getNewestFaceURL(message),
        rightNickname: logic.senderName,
        rightFaceUrl: logic.imLogic.userInfo.value.faceURL,
        showLeftNickname: !logic.isSingleChat,
        showRightNickname: !logic.isSingleChat,
        onFailedToResend: () => logic.failedResend(message),
        onClickItemView: () => logic.parseClickEvent(message),
        visibilityChange: (msg, visible) {
          logic.markMessageAsRead(message, visible);
        },
        onLongPressRightAvatar: () {},
        onTapLeftAvatar: () {
          logic.onTapLeftAvatar(message);
        },
        onVisibleTrulyText: (text) {
          logic.copyTextMap[message.clientMsgID] = text;
        },
        customTypeBuilder: _buildCustomTypeItemView,
        patterns: <MatchPattern>[
          MatchPattern(
            type: PatternType.email,
            onTap: logic.clickLinkText,
          ),
          MatchPattern(
            type: PatternType.url,
            onTap: logic.clickLinkText,
          ),
          MatchPattern(
            type: PatternType.mobile,
            onTap: logic.clickLinkText,
          ),
          MatchPattern(
            type: PatternType.tel,
            onTap: logic.clickLinkText,
          ),
        ],
        mediaItemBuilder: (context, message) {
          return _buildMediaItem(context, message);
        },
        onTapUserProfile: handleUserProfileTap,
         // 添加菜单回调
        onCopyMessage: logic.onCopyMessage,
        onQuoteMessage: logic.onQuoteMessage,
        onDeleteMessage: logic.onDeleteMessage,
        onRevokeMessage: logic.onRevokeMessage,
        onForwardMessage: logic.onForwardMessage,
        onMultiSelectMessage: logic.onMultiSelectMessage,
        onPinMessage: logic.onPinMessage,
        // 多选相关参数
        isMultiSelectMode: logic.isMultiSelectMode.value,
        isSelected: logic.isMessageSelected(message),
        onToggleSelection: logic.toggleMessageSelection,
        sendProgressSubject: logic.sendProgressSub,
        isSingleChat: logic.isSingleChat, // 传递聊天类型信息
        isMessagePinned: logic.isMessagePinned(message), // 传递该消息是否已置顶
        canPinMessage: logic.isAdminOrOwner, // 传递置顶权限信息
      );

  void handleUserProfileTap(({String userID, String name, String? faceURL, String? groupID}) userProfile) {
    final userInfo = UserInfo(userID: userProfile.userID, nickname: userProfile.name, faceURL: userProfile.faceURL);
    logic.viewUserInfo(userInfo);
  }

  Widget? _buildMediaItem(BuildContext context, Message message) {
    if (message.contentType != MessageType.picture && message.contentType != MessageType.video) {
      return null;
    }

    // 在多选模式下，返回null让ChatItemView使用默认的ChatVideoView或ChatPictureView
    // 这样可以确保多选逻辑在组件内部正确处理
    if (logic.isMultiSelectMode.value) {
      return null;
    }

    return GestureDetector(
      onTap: () async {
        try {
          IMUtils.previewMediaFile(
              context: context,
              message: message,
              onAutoPlay: (index) {
                return !logic.playOnce;
              },
              muted: logic.rtcIsBusy,
              onPageChanged: (index) {
                logic.playOnce = true;
              }).then((value) {
            logic.playOnce = false;
          });
        } catch (e) {
          IMViews.showToast(e.toString());
        }
      },
      child: Hero(
        tag: message.clientMsgID!,
        child: _buildMediaContent(message),
        placeholderBuilder: (BuildContext context, Size heroSize, Widget child) => child,
      ),
    );
  }

  Widget _buildMediaContent(Message message) {
    final isOutgoing = message.sendID == OpenIM.iMManager.userID;

    if (message.isVideoType) {
      return ChatVideoView(
        isISend: isOutgoing,
        message: message,
        sendProgressStream: logic.sendProgressSub.stream,
      );
    } else {
      return ChatPictureView(
        isISend: isOutgoing,
        message: message,
      );
    }
  }

  CustomTypeInfo? _buildCustomTypeItemView(_, Message message) {
    final data = IMUtils.parseCustomMessage(message);
    if (null != data) {
      final viewType = data['viewType'];
      if (viewType == CustomMessageType.call) {
        final type = data['type'];
        final content = data['content'];
        final view = ChatCallItemView(type: type, content: content);
        return CustomTypeInfo(view);
      } else if (viewType == CustomMessageType.deletedByFriend || viewType == CustomMessageType.blockedByFriend) {
        final view = ChatFriendRelationshipAbnormalHintView(
          name: logic.nickname.value,
          onTap: logic.sendFriendVerification,
          blockedByFriend: viewType == CustomMessageType.blockedByFriend,
          deletedByFriend: viewType == CustomMessageType.deletedByFriend,
        );
        return CustomTypeInfo(view, false, false);
      } else if (viewType == CustomMessageType.removedFromGroup) {
        return CustomTypeInfo(
          StrRes.removedFromGroupHint.toText..style = Styles.ts_8E9AB0_12sp,
          false,
          false,
        );
      } else if (viewType == CustomMessageType.groupDisbanded) {
        return CustomTypeInfo(
          StrRes.groupDisbanded.toText..style = Styles.ts_8E9AB0_12sp,
          false,
          false,
        );
      }else if (viewType == CustomMessageType.pinMessage || viewType == CustomMessageType.unpinMessage) {
         // 处理置顶通知消息
      final text = data['text'] ?? (viewType == CustomMessageType.pinMessage ? '置顶了一条消息' : '取消置顶了一条消息');
      return CustomTypeInfo(
        Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(4.r),
            border: Border.all(color: Styles.c_E8EAEF, width: 0.5),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.push_pin,
                size: 14.w,
                color: Styles.c_0089FF,
              ),
              4.horizontalSpace,
              Flexible(
                child: Text(
                  text,
                  style: TextStyle(
                    color: Styles.c_8E9AB0,
                    fontSize: 12.sp,
                  ),
                ),
              ),
            ],
          ),
        ),
        false, // 不需要气泡背景
        false, // 不需要ChatItemContainer
      );
    }
    }
    return null;
  }

  Widget? get _groupCallHintView => null;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: logic.willPop(),
      child: Obx(() {
        return Scaffold(
            backgroundColor: Styles.c_F0F2F6,
            appBar: TitleBar.chat(
              title: logic.isMultiSelectMode.value 
                  ? '已选择 ${logic.selectedMessageCount} 条消息'
                  : logic.nickname.value,
              member: logic.isMultiSelectMode.value 
                  ? '' 
                  : (logic.showGroupMemberCount.value ? logic.memberStr : ''),
              isMultiModel: logic.isMultiSelectMode.value, // 添加这个参数
              showCallBtn: false,
              onCloseMultiModel: logic.isMultiSelectMode.value 
                  ? logic.exitMultiSelectMode 
                  : logic.exit,
              onClickMoreBtn: logic.isMultiSelectMode.value 
                  ? null 
                  : logic.chatSetup,
              onClickCallBtn: logic.isMultiSelectMode.value 
                  ? null 
                  : (logic.isGroupChat ? null : logic.call),
              // 使用 actions 参数添加齿轮图标
              actions: logic.isMultiSelectMode.value 
                  ? null 
                  : [
                      GestureDetector(
                        onTap: logic.chatSetup,
                        child: Container(
                          padding: EdgeInsets.only(left: 36.w),
                          child: Icon(
                            Icons.settings,
                            size: 28.w,
                            color: Styles.c_0C1C33,
                          ),
                        ),
                      ),
                    ],
              // 多选模式下显示操作按钮
              // actions: logic.isMultiSelectMode.value ? [
              //   IconButton(
              //     icon: Icon(Icons.select_all),
              //     onPressed: logic.selectAllMessages,
              //     tooltip: '全选',
              //   ),
              //   IconButton(
              //     icon: Icon(Icons.forward),
              //     onPressed: logic.selectedMessageCount > 0 
              //         ? logic.forwardSelectedMessages 
              //         : null,
              //     tooltip: '转发',
              //   ),
              //   IconButton(
              //     icon: Icon(Icons.delete),
              //     onPressed: logic.selectedMessageCount > 0 
              //         ? logic.deleteSelectedMessages 
              //         : null,
              //     tooltip: '删除',
              //   ),
              // ] : null,
            ),
            body: SafeArea(
              child: WaterMarkBgView(
                text: '',
                path: logic.background.value,
                backgroundColor: Styles.c_FFFFFF,
                floatView: _groupCallHintView,
                    bottomView: logic.isMultiSelectMode.value 
                    ? _buildMultiSelectBottomBar() 
                    : ChatInputBox(
                        forceCloseToolboxSub: logic.forceCloseToolbox,
                        controller: logic.inputCtrl,
                        focusNode: logic.focusNode,
                        isNotInGroup: logic.isInvalidGroup,
                        directionalText: logic.directionalText(),
                        onCloseDirectional: logic.onClearDirectional,
                        quoteContent: logic.quoteContent,
                        quotedMessage: logic.quotedMessage.value,
                        onClearQuote: logic.clearQuoteMessage,
                        onSend: (v) => logic.sendTextMsg(),
                        onTapVoice: logic.onTapVoice,
                        toolbox: ChatToolBox(
                          onTapAlbum: logic.onTapAlbum,
                          onTapCall: logic.isGroupChat ? null : logic.call,
                          onTapCamera: logic.onTapCamera,
                          onTapFile: logic.onTapFile,
                        ),
                        voiceRecordBar: Obx(() => VoiceRecordBar(
                          onStartRecord: logic.onStartVoiceRecord,
                          onStopRecord: logic.onStopVoiceRecord,
                          onCancelRecord: logic.onCancelVoiceRecord,
                          isRecording: logic.isRecording.value,
                          recordDuration: logic.recordDuration.value,
                        )),
                      ),
                child: Column(
                  children: [
                    // 置顶消息区域
                    Obx(() => PinnedMessagesView(
                      pinnedMessages:  logic.pinnedMessages.toList(),
                      isExpanded: logic.showPinnedMessages.value,
                      currentUserId: OpenIM.iMManager.userID, // 传递当前用户ID
                      canRemovePinnedMessage: logic.isAdminOrOwner, // 传递移除置顶消息的权限
                      onTapMessage: (message) {
                        // 检查消息是否已被删除
                        logic.handlePinnedMessageTap(message);
                      },
                      onRemoveMessage: (message) {
                        logic.removePinnedMessage(message);
                      },
                      onToggleVisibility: () {
                        logic.togglePinnedMessagesVisibility();
                      },
                    )),
                    
                    // 聊天消息列表
                    Expanded(
                      child: ChatListView(
                        onTouch: () => logic.closeToolbox(),
                        itemCount: logic.messageList.length,
                        controller: logic.scrollController,
                        onScrollToBottomLoad: logic.onScrollToBottomLoad,
                        onScrollToTop: logic.onScrollToTop,
                        itemBuilder: (_, index) {
                          final message = logic.indexOfMessage(index);
                          return Obx(() => (logic.isGroupChat && !logic.isGroupDomainAvatarsReady.value)
                              ? SizedBox.shrink()
                              : _buildItemView(message));
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ));
      }),
    );
  }

    // 构建多选模式底部操作栏
  Widget _buildMultiSelectBottomBar() {
    return Container(
      height: 60.h,
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        border: Border(
          top: BorderSide(
            color: Styles.c_E8EAEF,
            width: 0.5,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 全选按钮
             // 全选按钮
        Expanded(
          child: InkWell(
            onTap: logic.selectAllMessages,
            child: Container(
              height: 60.h,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.select_all,
                    size: 24.w,
                    color: Styles.c_0C1C33,
                  ),
                  4.verticalSpace,
                  Text(
                    logic.areAllMessagesSelected ? '取消全选' : '全选',
                    style: Styles.ts_0C1C33_12sp,
                  ),
                ],
              ),
            ),
          ),
        ),
          
          // 分割线
          Container(
            width: 0.5,
            height: 40.h,
            color: Styles.c_E8EAEF,
          ),
          
          // 转发按钮
          Expanded(
            child: InkWell(
              onTap: logic.selectedMessageCount > 0 
                  ? logic.forwardSelectedMessages 
                  : null,
              child: Container(
                height: 60.h,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.forward,
                      size: 24.w,
                      color: logic.selectedMessageCount > 0 
                          ? Styles.c_0C1C33 
                          : Styles.c_8E9AB0,
                    ),
                    4.verticalSpace,
                    Text(
                      '转发',
                      style: logic.selectedMessageCount > 0 
                          ? Styles.ts_0C1C33_12sp 
                          : Styles.ts_8E9AB0_12sp,
                    ),
                  ],
                ),
              ),
            ),
          ),
          
          // 分割线
          Container(
            width: 0.5,
            height: 40.h,
            color: Styles.c_E8EAEF,
          ),
          
          // 删除按钮
          Expanded(
            child: InkWell(
              onTap: logic.selectedMessageCount > 0 
                  ? logic.confirmAndDeleteSelectedMessages 
                  : null,
              child: Container(
                height: 60.h,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.delete,
                      size: 24.w,
                      color: logic.selectedMessageCount > 0 
                          ? Colors.red 
                          : Styles.c_8E9AB0,
                    ),
                    4.verticalSpace,
                    Text(
                      '删除',
                      style: logic.selectedMessageCount > 0 
                          ? TextStyle(
                              fontSize: 12.sp,
                              color: Colors.red,
                            )
                          : Styles.ts_8E9AB0_12sp,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
